package com.houhanzhi.controller;


import com.google.code.kaptcha.Producer;
import com.houhanzhi.controller.request.SendCodeRequest;
import com.houhanzhi.enums.BizCodeEnum;
import com.houhanzhi.enums.SendCodeEnum;
import com.houhanzhi.response.JsonData;
import com.houhanzhi.service.NotifyService;
import com.houhanzhi.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author houhanzhi
 * @since 2025-01-02
 */
@RestController
@RequestMapping("/api/notify/v1")
@Slf4j
public class NotifyController {

    @Autowired
    private Producer producer;

    @Autowired
    private NotifyService notifyService;

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * redis过期时间
     */
    private static final int CAPTCHA_CODE_EXPIRED = 1000 * 10 * 60 ;

    /**
     * 获取图形验证码
     * @param request
     * @param response
     */
    @GetMapping("captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {
        String captchaText = producer.createText();
        log.info("验证码内容:{}",captchaText);

        // 存储redis，配置过期时间
        redisTemplate.opsForValue().set(getCaptchaKey(request),captchaText,CAPTCHA_CODE_EXPIRED, TimeUnit.MILLISECONDS);

        BufferedImage bu = producer.createImage(captchaText);
        try(ServletOutputStream outputStream = response.getOutputStream()) {
            ImageIO.write(bu, "jpg", outputStream);
            outputStream.flush();
        } catch (IOException e) {
            log.error("获取流异常:{}",e.getMessage());
        }
    }

    private String getCaptchaKey(HttpServletRequest request) {
        String ip = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");
        String key = "account-service:captcha:"+CommonUtil.MD5(ip+userAgent);
        log.info("验证码key:{}",key);
        return key;
    }

    /**
     * 发送短信验证码
     * @return
     */
    @PostMapping("send_code")
    public JsonData send_code(HttpServletRequest request, @RequestBody SendCodeRequest sendCodeRequest) {

        String key = getCaptchaKey(request);

        String cacheCaptchaCode = redisTemplate.opsForValue().get(key);

        String captchaCode = sendCodeRequest.getCaptchaCode();

        if(StringUtils.isNotEmpty(cacheCaptchaCode) && StringUtils.isNotEmpty(captchaCode) && cacheCaptchaCode.equalsIgnoreCase(captchaCode)){
            // 成功
            redisTemplate.delete(key);
            JsonData jsonData = notifyService.sendCode(SendCodeEnum.USER_REGISTER, sendCodeRequest.getTo());
            return jsonData;
        } else {
            return JsonData.buildResult(BizCodeEnum.CODE_ERROR);
        }
    }



}

